package com.movie.service.impl;

import com.movie.config.CustomUserDetails;
import com.movie.entity.Admin;
import com.movie.entity.User;
import com.movie.mapper.AdminMapper;
import com.movie.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 先尝试从用户表查找
        User user = userMapper.findByUsername(username);
        
        if (user != null) {
            // 找到普通用户，返回 CustomUserDetails
            return new CustomUserDetails(user);
        } 
        
        // 如果用户表找不到，再尝试从管理员表查找
        // 注意：Admin 实体也需要能适配 CustomUserDetails 或创建 AdminUserDetails
        // 这里暂时简化处理：如果找到管理员，仍旧返回包装了管理员信息的 CustomUserDetails，
        // 但需要 Admin 实体有 getId(), getUsername(), getPassword(), getRole() 等方法（或者适配）
        // 更好的方式是为 Admin 创建 AdminUserDetails
        Admin admin = adminMapper.findByUsername(username);
        if (admin != null) {
            // 找到管理员用户, 创建一个临时的 User 对象来包装 admin 信息
            // 假设 Admin 没有 role 字段，默认给管理员角色 (role=1)
            User adminAsUser = new User();
            adminAsUser.setId(admin.getId()); // 假设 Admin 有 getId()
            adminAsUser.setUsername(admin.getUsername());
            adminAsUser.setPassword(admin.getPassword());
            adminAsUser.setRole(1); // 明确设置管理员角色
            return new CustomUserDetails(adminAsUser); 
        }
        
        // 两个表都找不到，抛出异常
        throw new UsernameNotFoundException("User not found with username: " + username);
    }

    // loadAdminByUsername 方法也需要修改以返回 CustomUserDetails
    public UserDetails loadAdminByUsername(String username) throws UsernameNotFoundException {
        Admin admin = adminMapper.findByUsername(username);
        if (admin == null) {
            throw new UsernameNotFoundException("Admin not found with username: " + username);
        }
        // 管理员固定为 ROLE_ADMIN
        User adminAsUser = new User();
        adminAsUser.setId(admin.getId()); // 假设 Admin 有 getId()
        adminAsUser.setUsername(admin.getUsername());
        adminAsUser.setPassword(admin.getPassword());
        adminAsUser.setRole(1); // 明确设置管理员角色
        return new CustomUserDetails(adminAsUser);
    }
} 